package com.liuzh.fitnessplan.fragment

import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import com.liuzh.fitnessplan.R
import com.liuzh.fitnessplan.activity.LoginActivity
import com.liuzh.fitnessplan.database.bean.User
import com.liuzh.fitnessplan.databinding.FragmentMainBinding
import com.liuzh.fitnessplan.databinding.FragmentPersonalBinding
import com.liuzh.fitnessplan.tools.ActivitysManager
import com.liuzh.fitnessplan.tools.AppDataInfo
import com.liuzh.fitnessplan.tools.RoomDatabaseUtil

class PersonalFragment : Fragment() {
    private lateinit var bind : FragmentPersonalBinding
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val mView = LayoutInflater.from(activity).inflate(R.layout.fragment_personal,container,false)
        bind = FragmentPersonalBinding.bind(mView)
        setOnClick()
        return mView
    }

    private fun setOnClick() {
        val userId = AppDataInfo.instance.getSharedPreference(context!!).getInt("userId", 0)
        bind.userName.text = userId.toString()
        //登出
        bind.btnLogout.setOnClickListener {
            val builder = AlertDialog.Builder(activity!!)
                .setTitle("退出登录")
                .setMessage("确认退出？")
                .setPositiveButton("确认") { _, _ ->
                    logout()
                }
                .setNegativeButton("取消"){ dialog, _ ->
                    dialog.dismiss()
                }.create().show()
        }
        //修改密码
        bind.btnAlterPasswd.setOnClickListener {
            val view = LayoutInflater.from(activity).inflate(R.layout.alter_passwd_dialog,null,false)
            val builder = AlertDialog.Builder(activity!!)
                .setView(view)
                .setTitle("修改密码")
                .setPositiveButton("确认") { _, _ ->
                    val passwd: String = view.findViewById<EditText>(R.id.alter_passwd_edit).text.toString()
                    if(passwd.length<6){
                        Toast.makeText(activity!!,"密码不能小于6位",Toast.LENGTH_SHORT).show()
                        return@setPositiveButton
                    }
                    val user = User(AppDataInfo.instance.getId(activity!!),passwd)
                    RoomDatabaseUtil.instance.getDatabase(activity!!).userDao().update(user)
                    Toast.makeText(activity!!,"已修改密码",Toast.LENGTH_SHORT).show()
                }
                .setNegativeButton("取消"){ dialog, _ ->
                    dialog.dismiss()
                }.create().show()
        }
        //清除用户所有数据
        bind.btnClearAll.setOnClickListener {
            val builder = AlertDialog.Builder(activity!!)
                .setTitle("清除数据")
                .setMessage("确认清除？")
                .setPositiveButton("确认") { _, _ ->
                    clearAll(AppDataInfo.instance.getId(context!!),context!!)
                    Toast.makeText(activity!!,"已清除所有数据",Toast.LENGTH_SHORT).show()
                }
                .setNegativeButton("取消"){ dialog, _ ->
                    dialog.dismiss()
                }.create().show()
        }
    }

    private fun clearAll(userId : Int,context: Context){
        val db = RoomDatabaseUtil.instance.getDatabase(context).timeDao()
        val openItem = db.getOpenItem(userId)
        for(timePlan in openItem){
            cancelAlarm(timePlan.id)
        }
        db.delByUserId(userId)
        val intent = Intent("com.liuzh.UPDATE_UI")
        context.sendBroadcast(intent)
    }

    private fun cancelAlarm(id : Int){
        val intent = Intent("com.liuzh.ALARM_BROADCAST")
        //intent.putExtra("id",id)
        val pendingIntent = PendingIntent.getBroadcast(activity,id,intent,
            PendingIntent.FLAG_CANCEL_CURRENT)
        val alarmManager = activity!!.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        alarmManager.cancel(pendingIntent)
    }

    @SuppressLint("CommitPrefEdits")
    private fun logout(){
        ActivitysManager.instance.clearActivity()
        activity!!.startActivity(Intent(activity,LoginActivity::class.java))
        val sharedPreferences = AppDataInfo.instance.getSharedPreference(context!!).edit()
        sharedPreferences.putBoolean("isLogin",false)
        sharedPreferences.putInt("userId",0)
        sharedPreferences.apply()

    }
}